<template>
  <a-modal
    :title="titleMap[mode]"
    :visible="tableVisible"
    :destroyOnClose="true"
    :maskClosable="false"
    @cancel="handleCancel"
    width="95%">
    <a-spin :spinning="spinning" tip="加载中...">
      <a-table
        :columns="columns"
        bordered
        :data-source="newSource"
        :scroll="{ x: 800, y: 500 }"
        :pagination="false"
        :rowKey="(record, index) => { return record.projectId }"
        :defaultExpandAllRows="true"
        v-if="newSource.length">
        <template slot="promote" slot-scope="text,record">
          <span>
            {{ rateCompute(record.preActual, record.budget) }}
          </span>
        </template>
        <template slot="budget" slot-scope="text,record">
          <div class="editable-cell">
            <div v-if="editable" class="editable-cell-input-wrapper">

              <div v-if="editableData[record.projectId]">
                <a-input
                  v-model="editableData[record.projectId]['budget']"
                  @pressEnter="save(editableData[record.projectId])"
                  type="number"
                  @change="e => e.target.value = e.target.value.replace(/^0+(\d)|[^\d]+/g, '')"
                  @blur="onBlur($event, record.projectId, editableData[record.projectId])" />
                <a-icon
                  type="check"
                  @click="save(editableData[record.projectId])"
                  style="margin-right: 20px;" />
                <a-popconfirm title="确定取消?" @confirm="cancel(record)">
                  <a-icon type="close" />
                </a-popconfirm>
              </div>
              <div v-else>{{ text }}</div>
            </div>
            <div v-else class="editable-cell-text-wrapper">
              <div v-if="record.children == null">
                {{ text || ' ' }}
                <a-icon type="edit" @click="edit(record)" />
              </div>
              <div v-else>
                {{ text || ' ' }}
              </div>
            </div>
          </div>
        </template>
      </a-table>
    </a-spin>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">
        关闭
      </a-button>
      <a-button type="primary" :visible="visibleBtn" :loading="loadingBtn" @click="handleSubmit">
        保存
      </a-button>
    </template>
  </a-modal>
</template>

<script>
import { getBudgetsLaunch, addBudgets, detailBudgets, editBudgets } from '@/api/budget'
import { cloneDeep } from 'lodash-es'
export default {
    data () {
        return {
            tableVisible: false,
            dataSource: [],
            newSource: [], // 变化的源数据
            spinning: true,
            columns: [], // 头部表单

            editableData: {}, // 修改的位置数据
            previousData: {}, // 上一次的值
            editable: false, // 是否编辑

            // 接口参数
            addForm: {
                storeId: '',
                budgetType: '',
                budgetDate: '',
                title: '',
                description: ''
            },
            visibleBtn: false,
            loadingBtn: false,
            projects: [],
            mode: 'add',
            titleMap: {
                add: '填报月度预算',
                edit: '修改月度预算'
            },
            rowData: '',
            projectId: '',
            oldBudget: 0// 旧的预算金额
        }
    },
    methods: {
        // 计算比率
        // 本月比上月情况=（本月数字-上月数字）/上月数字，如果本月大于上月，结果就是正数，即上升，反之为下降
        rateCompute (a, b) {
            // if (a > 0 && b > 0) {
            //     if (a < b) return ((((b - a) / a) * 100).toFixed(2)) + '%'
            //     else if (b < a) return  ((((b - a) / a) * 100).toFixed(2)) + '%'
            //     else return '0%'
            // } else {
            //     if (a == 0 && b > a) return '100%'
            //     else return '0%'
            // }

            if (a > 0 && b > 0) {
                return ((((b - a) / a) * 100).toFixed(2)) + '%'
            } else {
                if (a == 0 && b > a) return '100%'
                else return '0%'
            }
        },
        edit (row) {
            this.editable = true
            this.editableData[row.projectId] = cloneDeep(row)
            // this.projectId = row.projectId
        },
        save (row) {
            this.editable = false

            this.calculate(row)
        },
        // 取消
        cancel (row) {
            this.editable = false

            this.getObj2(this.newSource, row.projectId, Number(this.oldBudget))
            delete this.editableData[row.projectId]

            // this.getObj(this.newSource, row.projectId, Number(this.oldBudget), row, callback)

            // function callback(isFind, _this, row) {
            //     if (isFind) {
            //         _this.fun2(row)
            //     }
            // }
            this.oldBudget = 0
        },
        onBlur (e, id, row) {
            // console.log(e)
            // console.log(id)
            const { value } = e.target
            // this.editableData[id].budget=value
            // console.log(this.editableData[id])
            // this.editable = false
            // this.calculate(row)
            // this.projectId = row.projectId
            this.oldBudget = this.getIdVal(this.dataSource, row.projectId)

            this.getObj2(this.newSource, row.projectId, Number(value))
        },
        // 计算
        calculate (row) {
            // 修改当前数据的值
            // this.getObj(this.newSource, row.projectId, Number(row.budget))
            // // 获取兄弟节点的父级id
            // let brotherParentId = row.parentProjectId
            // // 获取兄弟节点数据
            // let brotherParentArr =this.getBrotherParentId(this.newSource, brotherParentId)
            // // console.log(brotherParentArr)
            // // 兄弟数组的和  相差值
            // let ParentVal = brotherParentArr.reduce((accumulator, currentValue) => Number(accumulator) + Number(currentValue));
            // // console.log(ParentVal)
            // // 相关连的数据包括原来未改变的初始值
            // let joinedArr = this.get_level_all(this.dataSource, row.projectId)
            // joinedArr = joinedArr.filter(item => item.projectId != row.projectId)

            // // 处理直系父级
            // joinedArr = joinedArr.filter(item => item.projectId != row.parentProjectId)
            // this.getObj(this.newSource, row.parentProjectId, ParentVal)

            // // 相差值
            // joinedArr.forEach((item) => {
            //     this.getParentId(this.newSource, item.projectId,Number(ParentVal))
            // });

            // delete this.editableData[row.projectId];
            this.fun1(row)
            delete this.editableData[row.projectId]
        },
        fun1 (row) {
            // if (row.inOrOut == 2) {
            //     if(Number(row.budget) > 0){
            //         this.getObj(this.newSource, row.projectId, Number('-' + row.budget), row, callback)
            //     }
            //     else{
            //         this.getObj(this.newSource, row.projectId, Number(row.budget), row, callback)
            //     }

            // } else {
            this.getObj(this.newSource, row.projectId, Number(row.budget), row, callback)

            // }
            // this.getObj(this.newSource, row.projectId, Number(row.budget), row, callback)
            function callback (isFind, _this, row) {
                if (isFind) {
                    _this.fun2(row)
                }
            }
        },
        fun2 (row) {
            // 获取兄弟节点的父级id
            const brotherParentId = row.parentProjectId
            // 获取兄弟节点数据
            const brotherParentArr = this.getBrotherParentId(this.newSource, brotherParentId)
            console.log(brotherParentArr)
            if (brotherParentArr.length > 0) {
                // 兄弟数组的和  相差值
                const ParentVal = brotherParentArr.reduce((accumulator, currentValue) => Number(accumulator) + Number(currentValue))
                if (ParentVal) {
                    this.fun3(row, ParentVal)
                }
            }
        },
        fun3 (row, ParentVal) {
            // 相关连的数据包括原来未改变的初始值
            const joinedArr = this.get_level_all(this.dataSource, row.projectId).filter(item => item.projectId != row.projectId)

            const _this = this
            // 相差值
            if (joinedArr.length > 0) {
                // console.log(_this.newSource)
                joinedArr.forEach((item) => {
                    _this.getParentId(_this.newSource, item.projectId, Number(ParentVal))
                })
            }
        },
        // 根据id ，找到当前元素的对象，并进行赋值
        getObj (data, id, val, row, callback) {
            let isFind = false
            data.find((item) => {
                if (item.projectId === id) {
                    if (val == 0) item.budget = '0'
                    else item.budget = Number(val)

                    item.promote = this.rateCompute(Number(item.preActual), Number(item.budget))
                    isFind = true
                } else if (item.children != null && item.children.length > 0) {
                    this.getObj(item.children, id, val, row, callback)
                }
            })
            if (isFind) {
                callback(isFind, this, row)
                return isFind
            }
        },
        // 根据id，等到某条数据
        getIdVal (data, id) {
            let budget = '0'
            data.find((item) => {
                if (item.projectId === id) {
                    budget = item.budget
                    return budget
                } else if (item.children != null && item.children.length > 0) {
                    this.getIdVal(item.children, id)
                }
            })
            return budget
        },
        getObj2 (data, id, val) {
            data.find((item) => {
                if (item.projectId === id) {
                    if (val == 0) item.budget = '0'
                    else item.budget = Number(val)
                    console.log(this.rateCompute(Number(item.preActual), Number(item.budget)))
                    item.promote = this.rateCompute(Number(item.preActual), Number(item.budget))
                    console.log(item)
                } else if (item.children != null && item.children.length > 0) {
                    this.getObj2(item.children, id, val)
                }
            })
        },
        // 根据id ，找到当前元素的对象，并进行赋值
        // getObj2(data, id, val) {
        //     data.find((item) => {
        //         if (item.projectId === id) {
        //             if (val == 0) item.budget = '0'
        //             else item.budget = Number(val)

        //             item.promote = this.rateCompute(Number(item.preActual), Number(item.budget))
        //             return true;
        //         } else if (item.children != null && item.children.length > 0) {
        //             this.getObj(item.children, id, val);
        //         }
        //         return false;
        //     });
        // },
        // 根据id，找到所有的上级id
        get_level_all (data, id, arr = []) {
            data.find((item) => {
                if (item.projectId === id) {
                    arr.push(item)
                    return true
                } else if (item.children != null && item.children.length > 0) {
                    arr = this.get_level_all(item.children, id, arr)
                    if (arr.length) {
                        arr.push(item)
                        return true
                    } else {
                        return false
                    }
                }
                return false
            })
            return arr
        },
        // 根据id，找到所有的同级数据
        getBrotherParentId (data, id, arr = []) {
            data.find((item) => {
                if (item.parentProjectId == id) {
                    // 收支类型，1：收入，2：支出，3：其它
                    // 支出:减
                    if (item.inOrOut == '2') {
                        if (Number(item.budget) > 0) {
                            arr.push((item.inOrOut == '2' ? Number(('-' + item.budget)) : Number(item.budget)))
                        } else {
                            arr.push(Number(item.budget))
                        }
                    } else {
                        arr.push(Number(item.budget))
                    }
                } else if (item.children != null && item.children.length > 0) {
                    this.getBrotherParentId(item.children, id, arr)
                }
            })
            return arr
        },
        // 根据相差值遍历相关的父级或祖级
        getParentId (arr, id, numDiffer) {
            // arr.forEach(item => {
            //     if (item.projectId == id) {
            //         item.budget = Number(item.budget) + Number(numDiffer)
            //         item.promote = this.rateCompute(item.preActual, item.budget)

            //     }
            //     if (item.children != null && item.children.length > 0) {
            //         this.getParentId(item.children, id, numDiffer)
            //     }
            // })

            arr.forEach(item => {
                if (item.projectId == id) {
                    item.budget = Number(this.sumChildren(item.children))
                    item.promote = this.rateCompute(item.preActual, item.budget)
                }
                if (item.children != null && item.children.length > 0) {
                    this.getParentId(item.children, id, numDiffer)
                }
            })
        },
        // 获取子集得计算和
        sumChildren (children) {
            let sum = 0
            children.map(item => {
                if (item.inOrOut == '2' && Number(item.budget) < 0) {
                    // console.log("fff",Number(('-' + Math.abs(Number(item.budget)))))
                    // console.log(sum,Number(item.budget))
                    sum += Number(item.budget)
                } else {
                    sum += item.inOrOut == '2' ? Number(('-' + item.budget)) : Number(item.budget)
                }
                // sum += item.inOrOut == '2' ? Number(item.budget) : Number(item.budget)
            })

            return Math.abs(sum)
        },
        // 显示
        open (mode = 'add', par) {
            this.mode = mode
            this.dataSource = []
            this.columns = []
            this.tableVisible = true
            this.addForm = par
            this.rowData = par
            if (this.mode == 'add') {
                const { budgetType, budgetDate, storeId } = this.addForm
                const parForm = {
                    type: budgetType,
                    budgetDate,
                    storeId
                }
                getBudgetsLaunch(parForm).then(res => {
                    const headers = res.data.headers
                    headers.map(item => {
                        if (item.hidden == false) this.operator(item)
                    })
                    this.columns.push({
                        title: '提升比率',
                        dataIndex: 'promote',
                        key: 'promote',
                        align: 'left',
                        width: 120,
                        scopedSlots: { customRender: 'promote' }
                    })
                    const row = res.data.rows
                    this.handNull(row)

                    this.dataSource = row
                    this.spinning = false
                    this.newSource = row
                })
            } else {
                console.log(par)
                detailBudgets(par.budgetId).then(res => {
                    if (res.code == 200) {
                        const sheet = res.data.sheet
                        this.addForm.title = sheet.title
                        const headers = sheet.headers
                        headers.map(item => {
                            if (item.hidden == false) this.operator(item)
                        })
                        this.columns.push({
                            title: '提升比率',
                            dataIndex: 'promote',
                            key: 'promote',
                            align: 'left',
                            width: 120,
                            scopedSlots: { customRender: 'promote' }
                        })
                        const row = sheet.rows

                        this.handNull(row)
                        this.newSource = row
                        // this.dataSource = row
                        this.dataSource = row
                        this.spinning = false
                    }
                })
            }
        },
        // 子集没数据，赋值为空 null
        handNull (data) {
            data.forEach((item) => {
                item.promote = this.rateCompute(item.preActual, item.budget)

                if (item.children.length == 0) {
                    item.children = null
                } else {
                    this.handNull(item.children)
                }
            })
        },
        // columns 表头赋值
        operator (item) {
            const obj = {}
            if (item.columnId == 'projectName') {
                obj['title'] = item.name
                obj.dataIndex = 'name'
                obj.key = 'name'
                obj.align = 'left'
            } else if (item.columnId == 'preActual') {
                obj['title'] = item.name
                obj.dataIndex = 'preActual'
                obj.key = 'preActual'
                obj.align = 'left'
                obj.width = 200
            } else if (item.columnId == 'budget') {
                obj['title'] = item.name
                obj.dataIndex = 'budget'
                obj.key = 'budget'
                obj.align = 'left'
                obj.width = 200
                obj.scopedSlots = { customRender: 'budget' }
            } else return
            this.columns.push(obj)
        },
        // 关闭
        handleCancel () {
            this.tableVisible = false
            this.editable = false
            this.$emit('close')
        },
        // 确认
        handleSubmit () {
            this.loadingBtn = true
            this.visibleBtn = true
            this.getArr(this.newSource)
            if (this.projects.length == 0) return

            const { budgetType, budgetDate, description, title, storeId } = this.addForm
            const par = {
                budgetType,
                budgetDate,
                projects: this.projects,
                description,
                title,
                storeId
            }
            if (this.mode == 'edit') par.budgetId = this.rowData.budgetId
            const Api = this.mode == 'add' ? addBudgets : editBudgets
            Api(par).then(res => {
                if (res.code === 200) {
                    this.$notification['success']({
                        message: '提示',
                        description: '保存成功！',
                        duration: 8
                    })
                    this.tableVisible = false
                    this.$emit('success')
                } else {
                    this.$notification['error']({
                        message: '提示',
                        description: res.message,
                        duration: 8
                    })
                }
                this.visibleBtn = false
                this.loadingBtn = false
            })
        },
        // 遍历表格并处理
        getArr (arr) {
            arr.map(item => {
                this.projects.push({ projectId: item.projectId, budgetAmount: item.budget })
                if (item.children != null && item.children.length > 0) {
                    this.getArr(item.children)
                }
            })
        }

    }
}
</script>
<style scoped></style>
